<?php

namespace app\queue\stomp;

use app\queue\BaseConsumer;
use common\model\UserModel;
use common\service\ChatService;
use common\service\MessageService;

class SendBatchCreateEntityDemandMessageConsumer extends BaseConsumer
{

    // 要消费的队列名
    public $queue = 'send_batch_create_entity_demand_message';

    // 连接名，对应 config/redis_queue.php 里的连接`
    public $connection = 'default';

    /**
     *
     * @param $data
     * @return mixed|void
     */
    public function doConsume($data)
    {
        try {
            $entityIds = $data["entity_ids"];
            $noteEntityIdsMapData = $data["note_entity_ids_map_data"];
            //找到相关的群
            $chatService = ChatService::getInstance();
            $chat = $chatService->selectBatchEntityChat($entityIds);

            if (!empty($chat)) {
                //去重
                $chatGlobalIds = array_keys(array_column(array_values($chat), null, 'global_id'));

                //邀请进群
                teamones_request('teamones-im', 'oauth/invite_chat_user', [
                    'data' => [
                        'chat_global_id' => $chatGlobalIds,
                        'user_id' => [request()->getUnionUserId()]
                    ]
                ]);

                $user = model(UserModel::class)->field("union_id as id,name")->find(request()->getUserId());

                foreach ($noteEntityIdsMapData as $demandId => $noteEntityIdsMapDataItem) {
                    $chatData = [];
                    foreach ($noteEntityIdsMapDataItem["entity_ids"] as $noteEntityIdsMapDataItemEntityId) {
                        if (!in_array($chat[$noteEntityIdsMapDataItemEntityId]["global_id"], $chatData)) {
                            $chatData[] = $chat[$noteEntityIdsMapDataItemEntityId];
                        }
                    }
                    $noteEntityIdsMapDataItem["chat_list"] = $chatData;
                    $noteEntityIdsMapData[$demandId] = $noteEntityIdsMapDataItem;
                }
                //发送需求提示消息
                foreach ($noteEntityIdsMapData as $demandId => $noteEntityIdsMapDataItem) {
                    $message = [
                        "type" => "create_entity_demand_message",
                        "replace" => ["user" => $user, "demand_id" => $demandId, "demand_type" => $noteEntityIdsMapDataItem["demand_type_list"]]
                    ];
                    foreach ($noteEntityIdsMapDataItem["chat_list"] as $chatItem) {
                        $chatService->pushEntityTaskMessage($message, $chatItem);
                    }
                }
            }

        } catch (\Throwable $e) {
            trace(format_exception_info($e), "ERR");
        }
    }

}
